<?php

namespace app\admin\controller\xiluhouse\user;

use app\common\controller\Backend;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 经纪人管理
 *
 * @icon fa fa-user
 */
class Lessor extends Backend
{

    protected $relationSearch = true;

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\xiluhouse\User;
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->with(['userprofile'])
                ->where($where)
                ->where('userprofile.is_broker', 1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => $v) {
                $v->mobile = preg_replace('/(\d{3})\d{4}(\d{4})/', '$1****$2', $v->mobile);
                $v->hidden(['password', 'salt']);
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    public function detail($ids = null)
    {
        $row = $this->model->get($ids, 'extension');
        if (!$row) {
            $this->error(__('No Results were found'));
        }

        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row->visible([
            'id',
            'is_broker_text',
            'nickname',
            'mobile',
            'avatar',
            'gender_text',
            'tags',
            'prov',
            'city',
            'college',
            'service_num',
            'take_look_num',
            'satisfaction_degree',
            'bio',
            'money',
            'pid',
            'share_qrcode',
            'successions',
            'maxsuccessions',
            'prevtime_text',
            'logintime_text',
            'loginip',
            'joinip',
            'jointime_text',
            'createtime_text',
            'is_broker',
            'status',
            'deal_num',
            'pick_num',
            'abandon_num',
            'deal_percent',
        ]);
        $this->view->assign("row", $row->toArray());
        return $this->view->fetch();
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids, 'extension');
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    if ($row->mobile != $params['mobile']) {
                        // 如果修改了手机号
                        // 判断是否存在该手机号
                        $exist = $this->model->where('id', 'neq', $row->id)->where('mobile', $params['mobile'])->find();
                        if ($exist) {
                            exception('已存在该手机号');
                        }
                        $params['username'] = $params['mobile'];
                    }
                    $exist = \app\common\model\xiluhouse\UserProfile::where('user_id', $row->id)->find();
                    $saveData = $params['extension'];
                    if ($exist) {
                        $exist->save($saveData);
                    } else {
                        $saveData['user_id'] = $row->id;
                        (new \app\common\model\xiluhouse\UserProfile)->save($saveData);
                    }
                    $result = $row->allowField(true)->save($params);
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error(__('No rows were deleted'));
            }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
